# coding=utf-8


import re
import logging
import xml.etree.cElementTree as ET
from retrying import retry

from src.android.adb.drive import ADB
from src.common.prj_path import get_abs_path

LOG = logging.getLogger()


# 通过元素定位,需要Android 4.0以上
class Element(object):
    def __init__(self):
        self.adb = ADB
        self.pattern = re.compile(r"\d+")
        self.ui_xml_path = get_abs_path('output', 'ui.xml')
        self.check_adb_connect()

    def check_adb_connect(self):
        devices = self.adb.get_adb_devices()
        if not devices:
            raise Exception('no devices have connect')

    @retry(wait_fixed=1000, stop_max_attempt_number=5)
    def ___dump_ui_xml(self):
        self.adb.dump_xml('/sdcard/ui.xml')

    @retry(wait_fixed=1000, stop_max_attempt_number=5)
    def ___get_ui_xml(self):
        self.adb.download_file('/sdcard/ui.xml', self.ui_xml_path)

    def __ui_dump(self):
        self.___dump_ui_xml()
        self.___get_ui_xml()

    def return_elements_attrib_not_none(self, attrib):
        element_list = []
        self.__ui_dump()
        tree = ET.ElementTree(file=self.ui_xml_path)
        tree_iter = tree.iter(tag="node")
        for elem in tree_iter:
            if attrib in elem.attrib and elem.attrib[attrib]:
                element_list.append(elem.attrib[attrib])
        return element_list

    def __find_element(self, attrib, attrib_string, return_list):
        self.__ui_dump()
        point_list = []
        tree = ET.ElementTree(file=self.ui_xml_path)
        tree_iter = tree.iter(tag="node")
        for elem in tree_iter:
            if elem.attrib[attrib] == attrib_string:
                bounds = elem.attrib["bounds"]
                coord = self.pattern.findall(bounds)
                Xpoint = (int(coord[2]) - int(coord[0])) / 2.0 + int(coord[0])
                Ypoint = (int(coord[3]) - int(coord[1])) / 2.0 + int(coord[1])
                if return_list:
                    return Xpoint, Ypoint
                point_list.append((Xpoint, Ypoint))
        return point_list

    def find_element_by_attrib(self, attrib, attrib_string, return_list=None):
        attrib_list = ["resource-id", "class", "text"]
        if attrib not in attrib_list:
            raise Exception('not support {} in {}'.format(attrib, attrib_list))
        return self.__find_element(attrib, attrib_string, return_list)


if __name__ == '__main__':
    a = Element()
    ADB.adb_connect('192.168.2.243')
    pp = a.find_element_by_attrib('class', 'android.widget.ListView')
    print(pp)
